﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using NHTU;


namespace NOMFinalSettlement.AppForm.Program
{
    public partial class fApplySign : Office2007Form
    {        
        FinalSettlementModel.TableNhomCongTrinh groupProject = null;
        FinalSettlementModel.TableQuyetDinhDauTu acceptInvestment = null;
        FinalSettlementModel.TableChuDauTu investor = null;
        FinalSettlementModel.TableHinhThucChonThau construct = null;
        FinalSettlementModel.TableCanBo examine = null;
        FinalSettlementModel.TableNguonVon capital = null;
        FinalSettlementModel.TableHoSo profileDB = null;
        FinalSettlementModel.TablePheDuyet approveProfile = null;
        FinalSettlementModel.TableNguonVon_PheDuyet capitalApprove = null;

        int idSelected = -1;
        int idApproveSelected = -1;

        DataTable approveTable = null;

        public fApplySign()
        {
            InitializeComponent();
        }

        private void fApplySign_Load(object sender, EventArgs e)
        {    
            enableProfileControl(false);

            //Khoi tạo lớp model của TableNguonVon_PheDuyet
            capitalApprove = new FinalSettlementModel.TableNguonVon_PheDuyet();

            // Khởi tạo lớp model của TableNhomCongTrinh
            groupProject = new FinalSettlementModel.TableNhomCongTrinh();
            groupProject.EventLoadData += new FinalSettlementModel.TableNhomCongTrinh.LoadData(OnLoadGroupProject);
            doLoadDataComboboxGroupProject();

            // Khởi tạo lớp model của TableQuyetDinhDauTu
            acceptInvestment = new FinalSettlementModel.TableQuyetDinhDauTu();
            acceptInvestment.EventLoadData += new FinalSettlementModel.TableQuyetDinhDauTu.LoadData(OnLoadAcceptInvestment);
            doLoadDataComboboxAcceptInvestment();

            // Khởi tạo lớp model của TableChuDauTu
            investor = new FinalSettlementModel.TableChuDauTu();
            investor.EventLoadData += new FinalSettlementModel.TableChuDauTu.LoadData(OnLoadInvestor);
            doLoadDataComboboxInvestor();

            // Khởi tạo lớp model của TableHinhThucChonThau
            construct = new FinalSettlementModel.TableHinhThucChonThau();
            construct.EventLoadData += new FinalSettlementModel.TableHinhThucChonThau.LoadData(OnLoadConstructName);
            doLoadDataComboboxConstructName();

            // Khởi tạo lớp model của TableCanBo
            examine = new FinalSettlementModel.TableCanBo();
            examine.EventLoadData += new FinalSettlementModel.TableCanBo.LoadData(OnLoadExamineData);
            doloadDataListUser();

            // Khởi tạo lớp model của TableNguonVon
            capital = new FinalSettlementModel.TableNguonVon();
            capital.EventLoadData += new FinalSettlementModel.TableNguonVon.LoadData(OnLoadCapitalData);
            doloadCapitalInvestment();

            // Khởi tạo lớp model của TblPheDuyet
            approveProfile = new FinalSettlementModel.TablePheDuyet();
            approveProfile.EventLoadData += new FinalSettlementModel.TablePheDuyet.LoadData(OnLoadApproveData);
            doloadApproveProfile();

            // Khởi tạo lớp model của TblHoSo
            profileDB = new FinalSettlementModel.TableHoSo();
            profileDB.EventLoadData += new FinalSettlementModel.TableHoSo.LoadData(OnLoadProfileData);
            doLoadDataApplySign();

        }
        
        void OnLoadGroupProject()
        {
            ISynchronizeInvoke i = (ISynchronizeInvoke)this;
            if (i.InvokeRequired)
            {
                FinalSettlementModel.TableNhomCongTrinh.LoadData tmpTableNhomCongTrinh = new FinalSettlementModel.TableNhomCongTrinh.LoadData(OnLoadGroupProject);
                i.BeginInvoke(tmpTableNhomCongTrinh, null);
                return;
            }
            doLoadDataComboboxGroupProject();
        }
        void OnLoadAcceptInvestment()
        {
            ISynchronizeInvoke i = (ISynchronizeInvoke)this;
            if (i.InvokeRequired)
            {
                FinalSettlementModel.TableQuyetDinhDauTu.LoadData tmpTableQuyetDinhDauTu = new FinalSettlementModel.TableQuyetDinhDauTu.LoadData(OnLoadAcceptInvestment);
                i.BeginInvoke(tmpTableQuyetDinhDauTu, null);
                return;
            }
            doLoadDataComboboxAcceptInvestment();
        }
        void OnLoadInvestor()
        {
            ISynchronizeInvoke i = (ISynchronizeInvoke)this;
            if (i.InvokeRequired)
            {
                FinalSettlementModel.TableChuDauTu.LoadData tmpTableChuDauTu = new FinalSettlementModel.TableChuDauTu.LoadData(OnLoadInvestor);
                i.BeginInvoke(tmpTableChuDauTu, null);
                return;
            }
            doLoadDataComboboxInvestor();
        }
        void OnLoadConstructName()
        {
            ISynchronizeInvoke i = (ISynchronizeInvoke)this;
            if (i.InvokeRequired)
            {
                FinalSettlementModel.TableHinhThucChonThau.LoadData tmpTableHinhThucChonThau = new FinalSettlementModel.TableHinhThucChonThau.LoadData(OnLoadConstructName);
                i.BeginInvoke(tmpTableHinhThucChonThau, null);
                return;
            }
            doLoadDataComboboxConstructName();
        }
        void OnLoadExamineData()
        {
            ISynchronizeInvoke i = (ISynchronizeInvoke)this;
            if (i.InvokeRequired)
            {
                FinalSettlementModel.TableCanBo.LoadData tmpDelegate = new FinalSettlementModel.TableCanBo.LoadData(OnLoadExamineData);
                i.BeginInvoke(tmpDelegate, null);
                return;
            }
            //Hàm xử lý
            doloadDataListUser();
        }
        void OnLoadCapitalData()
        {
            ISynchronizeInvoke i = (ISynchronizeInvoke)this;
            if (i.InvokeRequired)
            {
                FinalSettlementModel.TableNguonVon.LoadData tmpDelegate = new FinalSettlementModel.TableNguonVon.LoadData(OnLoadCapitalData);
                i.BeginInvoke(tmpDelegate, null);
                return;
            }
            //Hàm xử lý
            doloadCapitalInvestment();
        }
        void OnLoadProfileData()
        {
            ISynchronizeInvoke i = (ISynchronizeInvoke)this;
            if (i.InvokeRequired)
            {
                FinalSettlementModel.TableHoSo.LoadData tmpDelegate = new FinalSettlementModel.TableHoSo.LoadData(OnLoadProfileData);
                i.BeginInvoke(tmpDelegate, null);
                return;
            }
            //Hàm xử lý     
            doLoadDataApplySign();
        }
        void OnLoadApproveData()
        {
            ISynchronizeInvoke i = (ISynchronizeInvoke)this;
            if (i.InvokeRequired)
            {
                FinalSettlementModel.TablePheDuyet.LoadData tmpDelegate = new FinalSettlementModel.TablePheDuyet.LoadData(OnLoadApproveData);
                i.BeginInvoke(tmpDelegate, null);
                return;
            }
            //Hàm xử lý
            doloadApproveProfile();
        }

        #region Sự kiện
        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (!superValidator1.Validate())
            {
                MsgBox.Show("Vui lòng nhập đầy đủ các thông tin yêu cầu.", "Thông báo", NHTU.MsgBoxButton.Ok, NHTU.MsgBoxIcon.Stop);
                return;
            }            
            doUpdateInfoProfile();
            reloadControl();                
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!superValidator2.Validate())
            {
                MsgBox.Show("Vui lòng nhập đầy đủ các thông tin yêu cầu.", "Thông báo", NHTU.MsgBoxButton.Ok, NHTU.MsgBoxIcon.Stop);
                return;
            }
            if (idApproveSelected < 1)
            {
                doSave();
            }
            else
            {
                doUpdate();
            }
            reloadControl();
        }

        private void dataViewProfile_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            superValidator1.ClearFailedValidations();
            superValidator2.ClearFailedValidations();

            idSelected = MainApp.Self.appProcess.getIdGrid(dataViewProfile, e, null);

            if (idSelected < 1)
            {

                enableProfileControl(false);
                reloadControl();
            }
            else
            {
                enableProfileControl(true);

                //Lấy dữ liệu từ grid ra text box
                DataGridViewSelectedRowCollection selectRows = dataViewProfile.SelectedRows;
                foreach (DataGridViewRow row in selectRows)
                {
                    if (row.Cells[0].Value != null)
                    {
                        txtProjectName.Text = row.Cells[1].Value.ToString();
                        txtProjectCode.Text = row.Cells[2].Value.ToString();
                        cbbGroupProject.Text = row.Cells[3].Value.ToString();
                        cbbAcceptInvestment.Text = row.Cells[4].Value.ToString();
                        cbbInvestor.Text = row.Cells[5].Value.ToString();
                        dateAddDoc.Text = row.Cells[6].Value.ToString();
                        totalProject.Text = row.Cells[7].Value.ToString();
                        totalEstimates.Text = row.Cells[8].Value.ToString();
                        totalSettlement.Text = row.Cells[9].Value.ToString();
                        cbbConstructName.Text = row.Cells[10].Value.ToString();
                        cbbExamineUser.Text = row.Cells[11].Value.ToString();

                        doSearchApproveDataTable((int)row.Cells[0].Value);
                    }
                }
            }
        }

        private void btnAddCapital_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow r in dataGridCapitalInvestment.Rows)
            {
                if (r.Cells[1].Value.ToString() == cbbCapital.SelectedValue.ToString())
                {
                    MsgBox.Show("Dữ liệu này đã được nhập.", "Thông báo", NHTU.MsgBoxButton.Ok, NHTU.MsgBoxIcon.Stop);
                    return;
                }
            }
            dataGridCapitalInvestment.Rows.Add(0, cbbCapital.SelectedValue,
                                                cbbCapital.SelectedNode.Cells[0].Text,
                                                Convert.ToDouble(cbbCapital.SelectedNode.Cells[1].Text));
        }

        private void colDELETE_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow item in this.dataGridCapitalInvestment.SelectedRows)
            {
                dataGridCapitalInvestment.Rows.RemoveAt(item.Index);
            }
        }
        #endregion

        #region Hàm xử lý
        void doSearchApproveDataTable(int profileId)
        {
            DataRow[] dr = approveTable.Select(String.Format("HoSoId='{0}'",profileId.ToString()));
            if (dr.Count() > 0)
            {
                foreach (DataRow r in dr)
                {
                    idApproveSelected = (int)r["ID"];
                    txtLocation.Text = r["DiaDiem"].ToString();
                    dateStart.Text = r["TGKhoiCong"].ToString();
                    dateFinish.Text = r["TGHoanThanh"].ToString();
                    txtScale.Text = r["QuyMoDauTu"].ToString();
                    inputTotalSettlement.Text = r["GTQTDuocDuyet"].ToString();
                    inputConstructionCosts.Text = r["ChiPhiXayDung"].ToString();
                    inputEquipmentCosts.Text = r["ChiPhiThietBi"].ToString();
                    inputManagerCosts.Text = r["ChiPhiQLDA"].ToString();
                    inputConsultancyCosts.Text = r["ChiPhiTVDT"].ToString();
                    inputClearanceCosts.Text = r["ChiPhiBTGPMB"].ToString();
                    inputOtherCosts.Text = r["ChiPhiKhac"].ToString();
                    if (r["TrinhKy"].ToString() == "True")
                    {
                        chkApplySign.Checked = true;
                    }
                    else chkApplySign.Checked = false;

                    var capApp = capitalApprove.ListCapital_ApproveData((int)r["ID"]);
                    dataGridCapitalInvestment.Rows.Clear();
                    foreach (var cap in capApp)
                    {
                        dataGridCapitalInvestment.Rows.Add(cap.ID, cap.NguonVonId, cap.TblNguonVon.NguonVon, (double)cap.TblNguonVon.GiaTri);
                    }
                }
            }
            else
            {
                idApproveSelected = -1;
                txtLocation.Text = "";
                dateStart.Text = "";
                dateFinish.Text = "";
                txtScale.Text = "";
                inputTotalSettlement.Text = null;
                inputManagerCosts.Text = null;
                inputOtherCosts.Text = null;
                inputClearanceCosts.Text = null;
                inputConstructionCosts.Text = null;
                inputEquipmentCosts.Text = null;
                inputConsultancyCosts.Text = null;
                chkApplySign.Checked = false;
                dataGridCapitalInvestment.Rows.Clear();
            }
        }
        void doLoadDataApplySign()
        {
            dataViewProfile.Rows.Clear();
            DataTable dt = profileDB.ListUseProfileData();

            foreach (DataRow row in dt.Rows)
            {
                if (dataViewProfile.ColumnCount > 0)
                {
                    dataViewProfile.Rows.Add(row["ID"], row["TenDuAn"], row["MaDuAn"], row["NhomCongTrinh"], row["QuyetDinhDauTu"], row["ChuDauTu"],
                        row["NgayNhan"], row["TongDuAn"], row["TongDuToan"], row["DeNghiQuyetToan"], row["HinhThucChonThau"], row["CanBo"]);
                }
            }
            approveTable = approveProfile.ListApproveData();
        }
        //Data to Commbobox
        void doLoadDataComboboxGroupProject()
        {
            cbbGroupProject.DataSource = groupProject.ListGroupObjectData();
            cbbGroupProject.DisplayMember = "NhomCongTrinh";
            cbbGroupProject.ValueMember = "ID";
        }
        void doLoadDataComboboxAcceptInvestment()
        {
            cbbAcceptInvestment.DataSource = acceptInvestment.ListInvestmentData();
            cbbAcceptInvestment.DisplayMember = "QuyetDinhDauTu";
            cbbAcceptInvestment.ValueMember = "ID";
        }
        void doLoadDataComboboxInvestor()
        {
            cbbInvestor.DataSource = investor.ListInvestorData();
            cbbInvestor.DisplayMember = "ChuDauTu";
            cbbInvestor.ValueMember = "ID";
        }
        void doLoadDataComboboxConstructName()
        {
            cbbConstructName.DataSource = construct.ListBidData();
            cbbConstructName.DisplayMember = "HinhThucChonThau";
            cbbConstructName.ValueMember = "ID";
        }
        void doloadDataListUser()
        {
            cbbExamineUser.DataSource = examine.ListOfficerData();
            cbbExamineUser.DisplayMember = "CanBo";
            cbbExamineUser.ValueMember = "ID";
        }
        void doloadCapitalInvestment()
        {
            cbbCapital.DataSource = capital.ListCapitalData();
            cbbCapital.DisplayMembers = "NguonVon,GiaTri";
            cbbCapital.ValueMember = "ID";
        }
        void doloadApproveProfile()
        {
            approveTable = approveProfile.ListApproveData();
        }

        void doUpdateInfoProfile()
        {
            if (profileDB.checkProfileName(idSelected, txtProjectName.Text))
            {
                profileDB.updateProfile(idSelected,
                                        txtProjectName.Text,
                                        txtProjectCode.Value,
                                        (int)cbbGroupProject.SelectedValue,
                                        (int)cbbAcceptInvestment.SelectedValue,
                                        (int)cbbInvestor.SelectedValue,
                                        dateAddDoc.Value,
                                        (decimal)totalProject.Value,
                                        (decimal)totalEstimates.Value,
                                        (decimal)totalSettlement.Value,
                                        (int)cbbConstructName.SelectedValue,
                                        MainApp.Self.DBUSER.ID);
                profileDB.updateExamine(idSelected, (int)cbbExamineUser.SelectedValue);
            }
            else
            {
                MsgBox.Show("Dữ liệu này đã tồn tại. Vui lòng kiểm tra lại!", "Thông Báo", MsgBoxButton.YesNo, MsgBoxIcon.Question);
            }
        }

        void doUpdate()
        {
            if (approveProfile.checkApproveName(idApproveSelected, idSelected))
            {
                approveProfile.updateApprove(idApproveSelected,
                                            idSelected,
                                            txtLocation.Text,
                                            dateStart.Value,
                                            dateFinish.Value,
                                            txtScale.Text,
                                            (decimal)inputTotalSettlement.Value,
                                            (decimal)inputConstructionCosts.Value,
                                            (decimal)inputEquipmentCosts.Value,
                                            (decimal)inputManagerCosts.Value,
                                            (decimal)inputConsultancyCosts.Value,
                                            (decimal)inputClearanceCosts.Value,
                                            (decimal)inputOtherCosts.Value,
                                            chkApplySign.Checked,
                                            "",Convert.ToDateTime("01/01/0001"), "", 0, false, "");
                capitalApprove.deleteCapital_Approve(idApproveSelected);
                if (dataGridCapitalInvestment.Rows.Count > 0)
                {
                    foreach (DataGridViewRow row in dataGridCapitalInvestment.Rows)
                    {
                        capitalApprove.insertCapital_Approve(idApproveSelected, (int)row.Cells[1].Value);
                    }
                }
            }
            else
            {
                MsgBox.Show("Dữ liệu này đã tồn tại. Vui lòng kiểm tra lại!", "Thông Báo", MsgBoxButton.YesNo, MsgBoxIcon.Question);
            }
        }

        void doSave()
        {
            if(approveProfile.checkApproveName(-1,idSelected))
            {
                approveProfile.insertApprove(idSelected,
                                            txtLocation.Text,
                                            dateStart.Value,
                                            dateFinish.Value,
                                            txtScale.Text,
                                            (decimal)inputTotalSettlement.Value,
                                            (decimal)inputConstructionCosts.Value,
                                            (decimal)inputEquipmentCosts.Value,
                                            (decimal)inputManagerCosts.Value,
                                            (decimal)inputConsultancyCosts.Value,
                                            (decimal)inputClearanceCosts.Value,
                                            (decimal)inputOtherCosts.Value,
                                            chkApplySign.Checked,
                                            "",Convert.ToDateTime("01/01/0001"), "", 0, false, "");
                if (dataGridCapitalInvestment.Rows.Count > 0)
                {
                    foreach (DataGridViewRow row in dataGridCapitalInvestment.Rows)
                    {
                        capitalApprove.insertCapital_Approve(approveProfile.approveIdentity, (int)row.Cells[1].Value);
                    }
                }
            }
            else
            {
                MsgBox.Show("Dữ liệu này đã tồn tại. Vui lòng kiểm tra lại!", "Thông Báo", MsgBoxButton.YesNo, MsgBoxIcon.Question);
            }
        }
        #endregion

        #region Hàm dùng chung
        void enableProfileControl(bool yes)
        {
            btnEdit.Enabled = yes;
            btnSave.Enabled = yes;
            dataGridCapitalInvestment.Enabled = yes;
            cbbCapital.Enabled = yes;
            btnAddCapital.Enabled = yes;

            txtProjectName.Enabled = yes;
            txtProjectCode.Enabled = yes;
            cbbGroupProject.Enabled = yes;
            cbbAcceptInvestment.Enabled = yes;
            cbbInvestor.Enabled = yes;
            dateAddDoc.Enabled = yes;
            totalProject.Enabled = yes;
            totalEstimates.Enabled = yes;
            totalSettlement.Enabled = yes;
            cbbConstructName.Enabled = yes;
            cbbExamineUser.Enabled = yes;

            txtLocation.Enabled = yes;
            dateStart.Enabled = yes;
            dateFinish.Enabled = yes;
            txtScale.Enabled = yes;
            inputTotalSettlement.Enabled = yes;
            inputManagerCosts.Enabled = yes;
            inputOtherCosts.Enabled = yes;
            inputClearanceCosts.Enabled = yes;
            inputConstructionCosts.Enabled = yes;
            inputEquipmentCosts.Enabled = yes;
            inputConsultancyCosts.Enabled = yes;
        }
        void reloadControl()
        {
            idSelected = -1;
            idApproveSelected = -1;

            txtProjectName.Text = "";            
            txtProjectCode.Text = null;
            cbbGroupProject.Text = "";
            cbbAcceptInvestment.Text = "";
            cbbInvestor.Text = "";
            dateAddDoc.Text = "";
            totalProject.Text = null;
            totalEstimates.Text = null;
            totalSettlement.Text = null;
            cbbConstructName.Text = "";
            cbbExamineUser.Text = "";

            txtLocation.Text = "";
            dateStart.Text = "";
            dateFinish.Text = "";
            txtScale.Text = "";
            inputTotalSettlement.Text = null;
            inputManagerCosts.Text = null;
            inputOtherCosts.Text = null;
            inputClearanceCosts.Text = null;
            inputConstructionCosts.Text = null;
            inputEquipmentCosts.Text = null;
            inputConsultancyCosts.Text = null;
            dataGridCapitalInvestment.Rows.Clear();
        }
        #endregion

        
    }
}
